package com.tungse;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author : Tungse
 * @Date: 2025/7/8 17:40
 * @Description:
 */
public class LockTest {
    public static final Map<String, Integer> catchmap = new ConcurrentHashMap<>();


    public static void main(String[] args) throws InterruptedException {
        LockTest lockTest = new LockTest();
        Thread t1 = new Thread(() -> {
            lockTest.saveing(new String("school1"));
        });
        Thread t2 = new Thread(() -> {
            lockTest.saveing(new String("school2"));
        });
        Thread t3 = new Thread(() -> {
            lockTest.saveing(new String("school2"));
        });
        Thread t4 = new Thread(() -> {
            lockTest.saveing(new String("school1"));
        });
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t1.join();
        t2.join();
        t3.join();
        t4.join();
        System.out.println(catchmap);
    }


    public void saveing(String schoolName) {
        synchronized (schoolName.intern()){
            save(schoolName, 1);
        }
    }
    public void save(String schoolName, int num) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if(catchmap.containsKey(schoolName)) {
            catchmap.put(schoolName, catchmap.get(schoolName) + num);
//            catchmap.merge(schoolName, num, Integer::sum);
        } else {
            catchmap.put(schoolName, num);
        }
    }

}
